﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace winApp2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            DataTable dt = DB.GetTable("master", "select name from sysdatabases where dbid>4");
            cbDB.DisplayMember = "name";
            cbDB.DataSource = dt;//绑定DataTable

        }

        private void cbDB_SelectedIndexChanged(object sender, EventArgs e)
        {
            string db = cbDB.Text;
            //查询库的表
            string sql = "select name from sysobjects where xtype='u'";
            DataTable dt = DB.GetTable(db, sql);
            cbTable.DisplayMember = "name";
            cbTable.DataSource = dt;

        }

        private void cbTable_SelectedIndexChanged(object sender, EventArgs e)
        {
            //获取库名
            string db = cbDB.Text;            
            //查询表的前100行数据
            string sql = "select top 100 * from ["+cbTable.Text+"]";
            //获取数据
            DataTable dt = DB.GetTable(db, sql);
            //显示数据
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = dt;
            //封装字段信息
            List<FieldInfo> list = new List<FieldInfo>();

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                list.Add(new FieldInfo
                {
                    Name=dt.Columns[i].ColumnName,//字段名
                    DataType=dt.Columns[i].DataType.ToString()//字段类型
                });
            }
            //显示字段信息
            dataGridView2.DataSource = list;

            //代码生成
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("namespace Haha.bean{");
            sb.AppendLine("\tpublic class "+cbTable.Text+"{");
            foreach(FieldInfo f in list){
                sb.AppendLine("\t  public "+f.DataType+" "+f.Name+"{get;set;}");
            }
            sb.AppendLine("\t}");
            sb.AppendLine("}");
            textBox1.Text = sb.ToString();

            

        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Save
            StreamWriter sw = new StreamWriter(cbTable.Text + ".cs", false, Encoding.Default);
            sw.Write(textBox1.Text);
            sw.Close();

        }
    }
}
